<?php

namespace app\lib\MessageBus\works;

use app\common\model\click\UserCallback;
use app\common\model\promotion\PromotionLink;
use app\common\model\return_rule\ReturnRule;
use app\common\service\media\MediaService;
use app\lib\MessageBus\base\AbstractWork;


/**
 * 用户注册回传
 *
 * Class MemberLoginCpaCallBack
 * @package app\lib\MessageBus\works
 */
class MemberLoginCpaCallBack extends AbstractWork
{
    public function handler($message)
    {
        dump("用户注册回调打印开始 用户ID-" . $message['user_id'] . date("Y-m-d H:i:s"), $message);
        $userCallback = UserCallback::where('user_id', $message['user_id'])->findOrEmpty();

        if ($userCallback->isEmpty()) {
            $userCallback = UserCallback::create($message["user_callback"]);
        }
        if (isset($message['promotion_link_id']) && $message['promotion_link_id'] == 0) {
            return;
        }

        $returnRule = ReturnRule::where('promotion_link_id', $message['promotion_link_id'])->findOrEmpty();

        $promotionLink = PromotionLink::where('id',$message['promotion_link_id'])->findOrEmpty();

        //判断推广链有没有广告计划ID 没有就更新上去
        if (!$promotionLink->isEmpty()&&empty($promotionLink->ad_id)){
            $adId = MediaService::getAdId($message, $userCallback,$message['source'] ?? 0);
            $promotionLink->ad_id = $adId['ad_id']??0;
            $promotionLink->project_id = $adId['project_id']??0;
            $promotionLink->advertising_id = $adId['advertising_id']??0;
            $promotionLink->save();

        }

        if (!$returnRule->isEmpty()){
            // 注册
            if ($returnRule->register == 1) {
                MediaService::register($message, $userCallback, $message['source'] ?? 0);
            } else {
                dump("规则不回传注册信息 用户ID-" . $message['user_id']);
            }

            // 如果激活勾选的话，注册时同时传激活状态
            if ($returnRule->active == 1) {
                MediaService::active($message, $userCallback, $message['source'] ?? 0);
            } else {
                dump("规则不回传激活信息 用户ID-" . $message['user_id']);
            }
        }else{
            dump("规则不存在 用户ID-" . $message['user_id']);
        }


        dump("用户注册回调打印结束 用户ID-" . $message['user_id'] . date("Y-m-d H:i:s"), $message);
    }

}
